<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Msystem extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function dbindex()
    {
        //return $this->renderQrCode('5GT5FC');
    }
    
    public function getPermissionDB($number,$offset)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql  = '';
        $key = $this->getParamString('keyword');
        
        $sql = "SELECT pg.id AS pgid, pg.name_pm, pg.admin_id, pg.active AS activer, DATE_FORMAT(pg.created,'%d/%m/%Y') AS time, u.id, u.username FROM permission_group AS pg INNER JOIN `user` AS u ON pg.admin_id = u.id WHERE 1 = 1 ";
        
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND (pg.name_pm like '%%".$key."%%')";
        } 
        
        $sql .= "ORDER BY pg.id ASC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
       
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);   
    }
    
    public function getListAdminDB($number,$offset)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql  = '';
        $key = $this->getParamString('keyword');
        
        $sql = "SELECT u2.username AS u2username, u1.id, u1.username, u1.fullname, u1.dateofbirth, u1.email, u1.mobile, u1.`level` AS u1level, u1.active AS activer FROM `user` AS u1 INNER JOIN `user` AS u2 ON u1.admin_id = u2.id WHERE 1=1 ";
        
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND (u1.username like '%%".$key."%%' OR ";
            $sql .= " u1.fullname like '%%".$key."%%' OR ";
            $sql .= " u1.email like '%%".$key."%%' OR ";
            $sql .= " u1.mobile like '%%".$key."%%')";
        } 
        
        $sql .= "ORDER BY u1.id ASC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
       
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);
    }
    
    public function getPermissionList($id)
    {
        return $this->db->query('SELECT pg.name_pm, pa.id FROM permission_group AS pg INNER JOIN permission_account AS pa ON pa.id_gr = pg.id WHERE pa.id_user = '.$id)->result_object();
    }
    
    public function addAdminDb($admin_id)
    {
        $uname = $this->getParamString('username');
        $pword = md5(md5($uname).md5($this->getParamString('pword')));
        $arr = array(
                'username'         => $uname,
                'pword'            => $pword,
                'fullname'         => $this->getParamString('fullname'),
                'email'            => $this->getParamString('email'),
                'mobile'           => $this->getParamString('mobile'),
                'active'           => 1,
                'admin_id'         => $admin_id,
                'level'            => $this->getParamInt('typeAccount'),
                'created'          => date('Y-m-d H:i:s')
            );
        $this->db->insert('user', $arr);
        return 200;
    }
    
    public function editAdminDb($admin_id, $id)
    {
        $arr = array(
                'fullname'         => $this->getParamString('fullname'),
                'email'            => $this->getParamString('email'),
                'mobile'           => $this->getParamString('mobile'),
                'active'           => $this->getParamInt('active'),
                'admin_id'         => $admin_id,
                'level'            => $this->getParamInt('typeAccount')
            );
        $pass_new = $this->getParamString('pword');
        if(!in_array($pass_new, array(null, '', '0')))
        {
            $username = $this->db->query('SELECT username FROM user WHERE id = '.$id)->row_object()->username;
            $arr['pword'] = $pword = md5(md5($username).md5($pass_new));
        }
        $this->db->update('user', $arr, 'id = '.$id);
        return 200;
    }
    
	public function editStaffDb($admin_id, $id)
    {
        $arr = array(
                'fullname'         => $this->getParamString('fullname'),
                'email'            => $this->getParamString('email'),
                'mobile'           => $this->getParamString('mobile'),
                'active'           => $this->getParamInt('active'),
                'admin_id'         => $admin_id,
                'restaurant_id' => $this->getParamInt('restaurant_id'),
            );
        $pass_new = $this->getParamString('pword');
        if(!in_array($pass_new, array(null, '', '0')))
        {
            $username = $this->db->query('SELECT username FROM `staff` WHERE id = '.$id)->row_object()->username;
            $arr['pword'] = $pword = md5(md5($username).md5($pass_new));
        }
        $this->db->update('staff', $arr, 'id = '.$id);
        return 200;
    }
	
    public function selectTypeAccount($id)
    {
        $data = (object)array('1' => 'Quản trị hệ thống','2' => 'Quản trị','3' => 'Nhân viên', '4' => 'Nhóm khác');
        $html = '<option value = "">Loại tài khoản</option>';
        foreach($data AS $el=>$le)
        {
            if($el == $id)
            {
                $selected = 'selected="selected"';
            }else{
                $selected = '';
            }
            $html .= '<option value="'.$el.'" '.$selected.'>'.$le.'</option>';
        }
        return $html;
    }
    
    public function deleteAdminDB($id)
    {
        $this->db->query("DELETE FROM user WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        return 200;
    }

    
    
    public function getAdminid($id)
    {
        return $this->db->query('SELECT * FROM user WHERE id = '.$id)->row_object();
    }
     public function getStaffid($id)
    {
        return $this->db->query('SELECT * FROM `staff` WHERE id = '.$id)->row_object();
    }
	
	
    public function addPermissionDb($admin_id)
    {
        $arr = array(
                'name_pm'          => $this->getParamString('name_pm'),
                'active'           => 1,
                'admin_id'         => $admin_id,
                'created'          => date('Y-m-d H:i:s')
            );
        $this->db->insert('permission_group', $arr);
        return 200;
    }
    
    public function editPermissionDb($admin_id, $id)
    {
        $arr = array(
                'name_pm'          => $this->getParamString('name_pm'),
                'active'           => $this->getParamInt('active'),
                'admin_id'         => $admin_id
            );
        $this->db->update('permission_group', $arr, 'id = '.$id);
        return 200;
    }
    
    public function getPermissionDetailDb($id)
    {
        return $this->db->query('SELECT * FROM permission_group WHERE id = '.$id)->row_object();
    }
    
    public function deletePermissionDB($id)
    {
        //die(print_r($id));
        $this->db->query("DELETE FROM permission_group WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        return 200;
    }
    
    public function selectUser($id)
    {
        $html = '';
        $sql = "SELECT id,username,fullname FROM user WHERE level != 1 ORDER BY id ASC ";
        $q = $this->db->query($sql);
        $data = $q->result_array();
        foreach($data AS $le=>$el)
        {
            if($id == $el['id'])
            {
                $selected = " selected = 'selected' ";
            }else{
                $selected = " ";
            }
            $html .= "<option value=".$el['id']." ".$selected.">".$el['username']." ---|--- ".$el['fullname']."</option>";
        }
        return $html;
    }
    
    public function getModule()
    {
        $sql = "SELECT id,name_module,orderby FROM module WHERE active <> 0 AND show_permission = 1 ORDER BY orderby ASC ";
        return $this->db->query($sql)->result_object();
    }
    public function selectPermission($id)
    {
        $html = '';
        $sql = "SELECT id,name_pm FROM permission_group ORDER BY id ASC ";
        $q = $this->db->query($sql);
        $data = $q->result_array();
        foreach($data AS $le=>$el)
        {
            if($id == $el['id'])
            {
                $selected = " selected = 'selected' ";
            }else{
                $selected = " ";
            }
            $html .= "<option value=".$el['id']." ".$selected.">".$el['name_pm']."</option>";
        }
        return $html;
    }
    
    public function getPerModule($a,$b,$c)
    {
        $sql = "SELECT 
                    p.read_pm, p.save_pm, p.eidt_pm, p.del_pm,p.restore_pm
                FROM permission AS p
                    INNER JOIN module ON p.id_module = module.id
                WHERE
                    p.id_module = '".$b."' AND
                    p.id_pg = '".$a."' AND
                    p.id_user = '".$c."'
                ";
        return $this->db->query($sql)->row_object();
    }
    
    public function savePer()
    {
        $access = '0';
        $save = '0';
        $edit = '0';
        $delete = '0';
        $delete_pm = '0';
        $restore_pm = '0';
        
        $id_permission = $this->getParamInt('permission');
        $module = $this->getParamArray('module');
        $user = $this->getParamInt('user');
        $per = $this->getParamArray('per');
        foreach($module AS $le=>$el)
        {
            if(!in_array($per, array(null, '', '0')))
            {
                foreach($per AS $lel=>$leel)
                    {
                        switch($leel)
                        {
                            case 1:
                                $access = '1';
                                break;
                            case 2:
                                $save = '2';
                                break;
                            case 3:
                                $edit = '3';
                                break;
                            case 4:
                                $delete = '4';
                                break;
                            case 5:
                                $restore_pm = '5';
                                break;
                            default:
                                $delete_pm = '1';
                                break;
                        }
                    }
            }else{
                $delete_pm = '1';
            }
            
            $data = array(
                    "id_pg"         => $id_permission,
                    "id_module"     => $el,
                    "id_user"       => $user,
                    "read_pm"       => $access,
                    "save_pm"       => $save,
                    "eidt_pm"       => $edit,
                    "del_pm"        => $delete,
                    "restore_pm"    => $restore_pm,
                    "admin_id"      => $this->session->userdata('admin_id'),
                    "created"       => date("Y-m-d H:i:s"));
            try{$this->db->delete('permission', "id_pg = '".$id_permission."' AND id_module = '".$el."' AND id_user = '".$user."'");} catch(exception $e){}
            if($delete_pm == 1)
            {
                try{$this->db->delete('permission_account', "id_gr = '".$id_permission."' AND id_module = '".$el."' AND id_user = '".$user."'");} catch(exception $e){}
            }
            if($delete_pm != 1)
            {
                $data2 = array(
                            "id_user"   => $user,
                            "id_gr"     => $id_permission,
                            "id_module" => $el,
                            "created"   => date("Y-m-d H:i:s")
                            );
                $sqls = "SELECT id_user,id_gr FROM permission_account WHERE id_user = '".$user."' AND id_gr = '".$id_permission."'";
                if($this->db->query($sqls)->num_rows() < 1)
                {
                    try{$this->db->insert('permission_account', $data2);} catch(exception $e){}
                }
                try{$this->db->insert('permission', $data);} catch(exception $e){}
            }
        }
        
        return true;
    }
	
	public function getListStaffDB($number,$offset)
    {
        $limit = $offset ? intval($offset) : '0';
        $sql  = '';
        $key = $this->getParamString('keyword');
        //die('2');
        $sql = "SELECT u2.username AS u2username, u1.id, u1.username, u1.fullname, u1.dateofbirth, u1.email, u1.mobile, u1.`level` AS u1level, u1.active AS activer,r.name AS nameres FROM `staff` AS u1 INNER JOIN `user` AS u2 ON u1.admin_id = u2.id LEFT JOIN restaurant AS r ON r.id = u1.restaurant_id WHERE 1=1 ";
        
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND (u1.username like '%%".$key."%%' OR ";
            $sql .= " u1.fullname like '%%".$key."%%' OR ";
            $sql .= " u1.email like '%%".$key."%%' OR ";
            $sql .= " u1.mobile like '%%".$key."%%')";
        } 
        
        $sql .= "ORDER BY u1.id ASC";
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object(); //echo '<pre>';die(print_r($xs));
       
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);
    }
	
	public function deleteStaffDB($id)
    {
        $this->db->query("DELETE FROM `staff` WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        return 200;
    }
    
	 public function getListRestaurant($id)
    {
        $html = '';
        $sql = "SELECT id,name FROM restaurant ORDER BY id ASC ";
        $q = $this->db->query($sql);
        $data = $q->result_array();
        foreach($data AS $le=>$el)
        {
            if($id == $el['id'])
            {
                $selected = " selected = 'selected' ";
            }else{
                $selected = " ";
            }
            $html .= "<option value=".$el['id']." ".$selected.">".$el['name']."</option>";
        }
        return $html;
    }
	
	public function addStaffDb($admin_id)
    {
        $uname = $this->getParamString('username');
        $pword = md5(md5($uname).md5($this->getParamString('pword')));
        $arr = array(
                'username'         => $uname,
                'pword'            => $pword,
                'fullname'         => $this->getParamString('fullname'),
                'email'            => $this->getParamString('email'),
                'mobile'           => $this->getParamString('mobile'),
                'active'           => 1,
                'admin_id'         => $admin_id,
                'restaurant_id'    => $this->getParamInt('restaurant_id'),
                'created'          => date('Y-m-d H:i:s')
            );
			//die(''.print_r($arr))
;        $this->db->insert('staff', $arr);
        return 200;
    }
	
	
	
}
